package com.example.demo.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.demo.dto.UserDto;
import com.example.demo.excel.CacheKey;
import com.example.demo.excel.service.EasyExcelImportService;
import com.example.demo.excel.valid.ExcelValidException;
import com.example.demo.exception.BusinessException;
import com.example.demo.service.UserService;
import com.example.demo.util.BaseConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.stream.Collectors;

@Service("UserExcelImportServiceImpl")
@Slf4j
public class UserExcelImportServiceImpl implements EasyExcelImportService<UserDto> {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    UserService userService;

    @Override
    public void saveErrorForExcel(Map<Integer, String> errorMap, String version) throws ExcelValidException {
        BoundHashOperations<String, Object, Object> myImportOps = getMyImportOps(version);
        /**
         * errorMap 的key是错误信息，value是excel的一行数据
         */
        if (ObjectUtils.isNotEmpty(errorMap)) {
            for (Map.Entry<Integer, String> entry : errorMap.entrySet()) {
                // key以String存储
                String key = entry.getKey() + "";
                Object obj = myImportOps.get(key);
                if (ObjectUtils.isEmpty(obj)) {
                    myImportOps.put(key, entry.getValue());
                } else {
                    myImportOps.put(key, obj + "," + entry.getValue());
                }
            }
        }
    }

    private BoundHashOperations<String, Object, Object> getMyImportOps(String version) {
        return redisTemplate.boundHashOps(myImportKey(version));
    }

    private String myImportKey(String version) {
        return String.format(CacheKey.IMPORT_EXCEL_SUPPLIER_KEY, version);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savaSuccessForExcel(List<UserDto> entityList, String version, Map<String, Object> param) {
        if (CollectionUtils.isEmpty(entityList)) {
            return;
        }
        String errorMsgValue= "";
        Map<Integer, String> errorMap = new HashMap<>(16);
        try{
            for (UserDto userDto: entityList ) {
                log.error(JSON.toJSONString(userDto));

            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("导入数据异常#" + e);
            if (e instanceof BusinessException) {
                BusinessException businessException = (BusinessException) e;
                errorMsgValue = businessException.getMessage();
            } else {
                errorMsgValue = "未知异常";
            }
            errorMap.put(BaseConstants.IMPORT_FAIL, errorMsgValue);
        }
        // 存储错误信息
        if (errorMap.size() > 0) {
            saveErrorForExcel(errorMap, version);
        }
    }
}
